package com.transsion.clouddemo.core.ulo.upload

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.transsion.cloud_client_sdk.CloudSDKManager
import com.transsion.cloud_upload_sdk.utils.Utils
import com.transsion.clouddemo.R
import com.transsion.clouddemo.core.Custom.BaseInfoAdapter
import com.transsion.clouddemo.core.Custom.CloudClickListener
import com.transsion.clouddemo.core.Custom.utils.GsonUtils
import com.transsion.clouddemo.core.DataGenerator
import com.transsion.clouddemo.core.DataGenerator.Companion.downToUploadTest
import com.transsion.clouddemo.core.DataGenerator.Companion.getAllFilePathsInSDKDirectory
import com.transsion.clouddemo.core.DataGenerator.Companion.listAllFilesInDirectory
import com.transsion.clouddemo.core.ulo.down.DownFragment.Companion.TAG
import com.transsion.clouddemo.core.ulo.down.DownFragment.Companion.URL_FAIL
import com.transsion.clouddemo.core.ulo.down.DownMessageItem
import com.transsion.clouddemo.databinding.CloudUploadBinding
import java.io.File

class UploadFragment : Fragment(),Handler.Callback {

    private lateinit var mBinding: CloudUploadBinding


    private val easyDataList by lazy { DataGenerator.easyUpload }
    private val multiPathDataList by lazy { DataGenerator.multiPathUpload }
    private val multiObjectDataList by lazy { DataGenerator.multiObjectUpload }
    private val breakPointDataList by lazy { DataGenerator.breakPointUpload }


    private val easyAdapter by lazy { BaseInfoAdapter(easyDataList) }
    private val multiPathAdapter by lazy { BaseInfoAdapter(multiPathDataList) }
    private val multiObjectAdapter by lazy { BaseInfoAdapter(multiObjectDataList) }
    private val breakPointAdapter by lazy { BaseInfoAdapter(breakPointDataList) }

    private val mHandler = Handler(Looper.getMainLooper(), this)

    companion object {

        const val EASY_UPLOAD = 1000
        const val MULTI_PATH = 1001
        const val MULTI_OBJECT = 1002

        const val SUCCESS = "success_upload"
        const val FAIL = "fail_upload"
        const val CLOUD_EXIST = "cloud_data_exist"  //0为不存在  1为存在



        fun newInstance(): UploadFragment {
            return UploadFragment()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        mBinding = CloudUploadBinding.inflate(inflater, container, false)
        //初始化数据
        initdata()
        //初始化RecyclerView
        initInfoRecyclerView()
        //初始化简单上传按钮
        initEasyButton()
        //初始化多文件路径上传按钮
        initMultiPathButton()
        //初始化多文件对象上传按钮
        initMultiObjectButton()
        //初始化断点续传按钮
        initBreakPointButton()


        return mBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun handleMessage(msg: Message): Boolean {
        when (msg.what) {
            EASY_UPLOAD->{
                val item = DownMessageItem(msg.data.getString(SUCCESS)!!, msg.data.getString(FAIL)!!)
                easyDataList.add(item)
                easyAdapter.notifyDataSetChanged()
                mBinding.easyUploadRecyclerView.scrollToPosition(easyDataList.size - 1)

            }
            MULTI_PATH->{
                val item = DownMessageItem(msg.data.getString(SUCCESS)!!, msg.data.getString(FAIL)!!)
                multiPathDataList.add(item)
                multiPathAdapter.notifyDataSetChanged()
                mBinding.multiPathUploadRecyclerView.scrollToPosition(multiPathDataList.size - 1)

            }
            MULTI_OBJECT->{
                val item = DownMessageItem(msg.data.getString(SUCCESS)!!, msg.data.getString(FAIL)!!)
                multiObjectDataList.add(item)
                multiObjectAdapter.notifyDataSetChanged()
                mBinding.multiObjectUploadRecyclerView.scrollToPosition(multiObjectDataList.size - 1)

            }
        }
        return true

    }


    fun initdata() {

    }

    fun initInfoRecyclerView() {

        mBinding.easyUploadRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = easyAdapter
        }
        mBinding.multiPathUploadRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = multiPathAdapter
        }
        mBinding.multiObjectUploadRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = multiObjectAdapter
        }
        mBinding.breakpointUploadRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = breakPointAdapter
        }
    }

    fun initEasyButton() {


        mBinding.buttonUploadEasy.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {

                mBinding.easyUploadRecyclerView.visibility = View.VISIBLE
                mBinding.buttonEasyDelete.visibility = View.VISIBLE

                Log.e(TAG, "使用简单上传的方式开始上传=================")
                mBinding.buttonUploadEasy.apply {
                    isEnabled=false
                    text = resources.getString(R.string.cloud_uploading)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }

                //开始上传
                CloudSDKManager.getInstance()
                    .uploadEasyFile(downToUploadTest) { key, info, response ->
                        Log.e(TAG, "key: $key")
                        Log.e(TAG, "info: $info")
                        Log.e(TAG, "response: $response")
                        Log.e(TAG, "上传的结果: ${info.success()}")


                        val resultMap = GsonUtils.jsonToObject<Map<String, String>>(response)
                        resultMap.values.forEach {
                            val message = mHandler.obtainMessage(EASY_UPLOAD)
                            val bundle = Bundle().apply {
                                putString(SUCCESS, it)
                                putString(FAIL,DataGenerator.codeToReason[info.code])
                            }
                            if (info.success()) {
                                easyDataList[0].fail = ""
                                easyDataList[1].fail = ""
                            }
                            message.data = bundle
                            mHandler.sendMessage(message)

                        }

                        mBinding.buttonUploadEasy.apply {
                            isEnabled=true
                            text = resources.getString(R.string.cloud_upload)
                            setTextColor(context.getColor(R.color.cloud_text_default))
                        }
                    }

            }

        })

        mBinding.buttonEasyDelete.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                if (easyDataList.size > 2) {  // 检查列表是否有超过两项
                    Log.e(TAG,"开始删除数据=================")
                    easyDataList.subList(2, easyDataList.size).clear()
                }
                easyDataList[0].fail = "下载失败!"
                easyDataList[1].fail = "失败原因："
                easyAdapter.notifyDataSetChanged()
            }
        })
    }



    fun initMultiPathButton() {


        mBinding.buttonUploadPath.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {

                mBinding.multiPathUploadRecyclerView.visibility = View.VISIBLE
                mBinding.buttonPathDelete.visibility = View.VISIBLE

                Log.e(TAG, "使用多文件（路径）上传的方式开始上传=================")
                mBinding.buttonUploadPath.apply {
                    isEnabled=false
                    text = resources.getString(R.string.cloud_uploading)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }
                val paths = getAllFilePathsInSDKDirectory()
                //开始上传
                CloudSDKManager.getInstance()
                    .uploadPath(paths) { key, info, response ->
                        Log.e(TAG, "key: $key")
                        Log.e(TAG, "info: $info")
                        Log.e(TAG, "response: $response")
                        Log.e(TAG, "下载的结果: ${info.success()}")

                        if (paths.isEmpty()) {
                            val message = mHandler.obtainMessage(MULTI_PATH)
                            val bundle = Bundle().apply {
                                putString(SUCCESS, "无")
                                putString(FAIL,DataGenerator.codeToReason[info.code])
                            }
                            if (info.success()) {
                                multiPathDataList[0].fail = ""
                                multiPathDataList[1].fail = ""
                            }
                            message.data = bundle
                            mHandler.sendMessage(message)
                        } else {
                            paths.forEach{path ->
                                val message = mHandler.obtainMessage(MULTI_PATH)
                                val bundle = Bundle().apply {
                                    putString(SUCCESS, path)
                                    putString(FAIL,DataGenerator.codeToReason[info.code])
                                }
                                if (info.success()) {
                                    multiPathDataList[0].fail = ""
                                    multiPathDataList[1].fail = ""
                                }
                                message.data = bundle
                                mHandler.sendMessage(message)
                            }
                        }

                        mBinding.buttonUploadPath.apply {
                            isEnabled=true
                            text = resources.getString(R.string.cloud_upload)
                            setTextColor(context.getColor(R.color.cloud_text_default))
                        }
                    }


            }

        })

        mBinding.buttonPathDelete.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                if (multiPathDataList.size > 2) {  // 检查列表是否有超过两项
                    Log.e(TAG,"开始删除数据=================")
                    multiPathDataList.subList(2, multiPathDataList.size).clear()
                }
                multiPathDataList[0].fail = "下载失败!"
                multiPathDataList[1].fail = "失败原因："
                multiPathAdapter.notifyDataSetChanged()
            }
        })
    }


    fun initMultiObjectButton() {

        mBinding.buttonUploadObject.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {
                mBinding.multiObjectUploadRecyclerView.visibility = View.VISIBLE
                mBinding.buttonMultiObjectDelete.visibility = View.VISIBLE

                Log.e(TAG, "使用多文件（对象）上传的方式开始上传=================")
                mBinding.buttonUploadObject.apply {
                    isEnabled=false
                    text = resources.getString(R.string.cloud_uploading)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }
                val files = listAllFilesInDirectory(Utils.sdkDirectory())
                //开始上传
                CloudSDKManager.getInstance()
                    .uploadFile(listAllFilesInDirectory(Utils.sdkDirectory())) { key, info, response ->
//                        .uploadFile(File(Utils.sdkDirectory()).listFiles()!!.toList()) { key, info, response ->

                        Log.e(TAG, "key: $key")
                        Log.e(TAG, "info: $info")
                        Log.e(TAG, "response: $response")
                        Log.e(TAG, "上传的结果: ${info.success()}")

                        if (files.isEmpty()) {
                            val message = mHandler.obtainMessage(MULTI_OBJECT)
                            val bundle = Bundle().apply {
                                putString(SUCCESS, "无")
                                putString(FAIL,DataGenerator.codeToReason[info.code])
                            }
                            if (info.success()) {
                                multiObjectDataList[0].fail = ""
                                multiObjectDataList[1].fail = ""
                            }
                            message.data = bundle
                            mHandler.sendMessage(message)
                        } else{
                            files.forEach{file ->
                                val message = mHandler.obtainMessage(MULTI_OBJECT)
                                val bundle = Bundle().apply {
                                    putString(SUCCESS, file.name)
                                    putString(FAIL,DataGenerator.codeToReason[info.code])
                                }
                                if (info.success()) {
                                    multiObjectDataList[0].fail = ""
                                    multiObjectDataList[1].fail = ""
                                }
                                message.data = bundle
                                mHandler.sendMessage(message)
                            }
                        }
                        mBinding.buttonUploadObject.apply {
                            isEnabled=true
                            text = resources.getString(R.string.cloud_upload)
                            setTextColor(context.getColor(R.color.cloud_text_default))
                        }
                    }


            }
        })

        mBinding.buttonMultiObjectDelete.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                if (multiObjectDataList.size > 2) {  // 检查列表是否有超过两项
                    Log.e(TAG,"开始删除数据=================")
                    multiObjectDataList.subList(2, multiObjectDataList.size).clear()
                }
                multiObjectDataList[0].fail = "下载失败!"
                multiObjectDataList[1].fail = "失败原因："
                multiObjectAdapter.notifyDataSetChanged()
            }
        })
    }

    //标志是否是续传
    var isContinued = false

    fun initBreakPointButton() {


        mBinding.buttonUploadBreakpoint.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {

                Log.e(TAG, "使用断点续传的方式开始上传=================")
                mBinding.buttonUploadBreakpoint.apply {
                    isEnabled=false
                    text = resources.getString(R.string.cloud_uploading)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }
                val files = listAllFilesInDirectory(Utils.sdkDirectory())
                if (isContinued) {
                    //开始上传
                    CloudSDKManager.getInstance()
                        .uploadFile(files) { key, info, response ->
                            Log.e(TAG, "key: $key")
                            Log.e(TAG, "info: $info")
                            Log.e(TAG, "response: $response")
                            Log.e(TAG, "上传的结果: ${info.success()}")

                            if (files.isEmpty()) {
                                val message = mHandler.obtainMessage(MULTI_OBJECT)
                                val bundle = Bundle().apply {
                                    putString(SUCCESS, "无")
                                    putString(FAIL,DataGenerator.codeToReason[info.code])
                                }
                                if (info.success()) {
                                    breakPointDataList[0].fail = ""
                                    breakPointDataList[1].fail = ""
                                }
                                message.data = bundle
                                mHandler.sendMessage(message)
                            } else{
                                files.forEach{file ->
                                    val message = mHandler.obtainMessage(MULTI_OBJECT)
                                    val bundle = Bundle().apply {
                                        putString(SUCCESS, file.name)
                                    }
                                    if (!info.success()) {
                                        bundle.putString(URL_FAIL, info.message)
                                    }
                                    message.data = bundle
                                    mHandler.sendMessage(message)
                                }
                            }
                            mBinding.buttonUploadObject.apply {
                                isEnabled=true
                                text = resources.getString(R.string.cloud_upload)
                                setTextColor(context.getColor(R.color.cloud_text_default))
                            }
                        }
                    isContinued=false
                } else {
                    isContinued=false
                }
            }
        })

        mBinding.buttonUploadBreakpointPause.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {

                isContinued = true
                mBinding.buttonUploadObject.apply {
                    isEnabled=true
                    text = resources.getString(R.string.cloud_upload)
                    setTextColor(context.getColor(R.color.cloud_text_default))
                }



            }
        })


        mBinding.buttonBreakpointDelete.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                if (breakPointDataList.size > 2) {  // 检查列表是否有超过两项
                    Log.e(TAG,"开始删除数据=================")
                    breakPointDataList.subList(2, breakPointDataList.size).clear()
                }
                breakPointDataList[0].fail = "下载失败!"
                breakPointDataList[1].fail = "失败原因："
                breakPointAdapter.notifyDataSetChanged()
            }
        })
    }




    /**
     * 查询某目录下的文件个数（没有递归，当前目录下包含的必须是文件）
     */
    fun getFileCount(directoryPath: String): Int {
        val directory = File(directoryPath) // 创建表示目录的File对象
        if (!directory.exists() || !directory.isDirectory) {
            return 0 // 如果目录不存在或不是一个目录，返回0
        }
        val files = directory.listFiles() // 列出目录中的所有文件和子目录
        return files?.size ?: 0 // 返回文件和子目录的数量，如果为空则返回0
    }


}

